package com.yanhui.api.file;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description ${END}
 * @Author yanhui
 * @Date 2018-12-16 23:10
 */
public class PoiApi {

    /**
     * 生成doc文件
     * @param inputFilePath 模板doc文件
     * @param outputFilePath 输出doc文件
     * @param map 数据
     * @throws Exception
     */
    public static void createDoc(String inputFilePath, String outputFilePath, Map<String, String> map) throws Exception {
        InputStream is = new FileInputStream(inputFilePath);
        HWPFDocument doc = new HWPFDocument(is);
        // 返回覆盖整个文档的范围，但不包括任何页眉和页脚。
        Range range = doc.getRange();
        for(Map.Entry<String, String> entry : map.entrySet()){
            range.replaceText(entry.getKey(), entry.getValue());
        }
        String fileName = outputFilePath;
        File f = new File(fileName);
        if(!f.exists()){
            f.createNewFile();
        }
        doc.write(new FileOutputStream(fileName));
        // 释放资源
        closeStream(is);
    }

    public static void main(String[] args) throws Exception {
        String inputFilePath = "C:\\temp.doc";
        String outputFilePath = "C:\\Users\\admin\\Desktop\\new2.doc";
        Map<String, String> map = new HashMap<String, String>();
        map.put("$projectName$", "唯美酒店");
        map.put("$projectName2$", "唯美酒店2");
        createDoc(inputFilePath, outputFilePath, map);
    }

    /**
     * 关闭输入流
     */
    private static void closeStream(InputStream is) {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
